<?php 
	
	/**
	 * @author marcio.alves
	 *
	 */
	class Logger extends Base {
		
		private static $logger = null;
		private static $datePattern = null;
		private static $level = null;
		private static $printEcho = false;
		
		public static function getLevel() {
			if( self::$level == null )
				self::$level = self::getConfig("logger-level");
			return self::$level;
		}
		
		public static function getDatePattern() {
			if( self::$datePattern == null )
				self::$datePattern = self::getConfig("date-format");
				
			return self::$datePattern;	
		}
		
		public static function getLogger() {
			if( self::$logger != null ) return self::$logger;
			
			$root = Config::getRoot();
			$path = $root . "/log/";
			
			if( !opendir($path) ) mkdir($path);

			self::$logger = fopen($path . "/application.log","a");
			
			return self::$logger;
		}
		
		private static function closeLogger() {
			fclose(self::$logger);	
		}
		
		private static function getConfig($name) {
			$arr = Config::getConfig("configuration");
			if( isset($arr[$name]) ) return $arr[$name];
			else die("Configuration '" . $name . "' not found");
		}		
		
		private static function makePrefix($type, $clazz) {
			$prefix = "[$type] ";
			$format = self::getDatePattern();
			$prefix .= date($format);
			$temp = Util::get_class($clazz);
			
			if( $temp == "" ) {
				$prefix .= " [" . $clazz . "] - ";	
			} else {
				$prefix .= " [" . $temp . "] - ";
			}
			return $prefix;
		}
		
		public static function debug($clazz, $message) {
			if( self::getLevel() == "debug" ) {
				$temp = self::getLogger();
				$prefix = self::makePrefix("DEBUG", $clazz);			
				$msg = "\n" . $prefix . $message;			
				fwrite($temp, $msg);
				self::printLog($msg);
			}
		}
		
		public static function info($clazz, $message) {
			if( self::getLevel() == "info" ) {
				$temp = self::getLogger();
				$prefix = self::makePrefix("INFO", $clazz);			
				$msg = "\n" . $prefix . $message;			
				fwrite($temp, $msg);
				self::printLog($msg);
			}
		}
		
		public static function error($clazz, $message) {
			if( self::getLevel() == "error" ) {
				$temp = self::getLogger();
				$prefix = self::makePrefix("ERROR", $clazz);
				$msg = "\n" . $prefix . $message;			
				fwrite($temp, $msg);
				self::printLog($msg);
			}
		}
		
		public static function printLog($message) {
			if( self::$printEcho ) echo $message . "<br />";
		}
	}
?>